#include "utils/config_manager.h"
#include "json_utils.h"
#include <fstream>
#include <sstream>
#include <iostream>

namespace hft {

bool ConfigManager::loadConfig(const std::string& filename) {
    try {
        std::lock_guard<std::mutex> lock(mutex_);
        
        // 加载JSON文件
        nlohmann::json config = JsonUtils::loadFromFile(filename);
        
        // 加载CTP配置
        if (config.contains("ctp")) {
            auto& ctp = config["ctp"];
            ctp_config_.front_address = ctp["front_address"].get<std::string>();
            ctp_config_.broker_id = ctp["broker_id"].get<std::string>();
            ctp_config_.user_id = ctp["user_id"].get<std::string>();
            ctp_config_.password = ctp["password"].get<std::string>();
            ctp_config_.app_id = ctp["app_id"].get<std::string>();
            ctp_config_.auth_code = ctp["auth_code"].get<std::string>();
        }
        
        // 加载交易参数
        if (config.contains("trading")) {
            auto& trading = config["trading"];
            trading_params_.max_position = trading["max_position"].get<double>();
            trading_params_.max_order_size = trading["max_order_size"].get<double>();
            trading_params_.max_slippage = trading["max_slippage"].get<double>();
            trading_params_.min_liquidity = trading["min_liquidity"].get<int64_t>();
            trading_params_.risk_limit = trading["risk_limit"].get<double>();
            trading_params_.max_retry_count = trading["max_retry_count"].get<int>();
            trading_params_.retry_interval_ms = trading["retry_interval_ms"].get<int>();
            trading_params_.timeout_ms = trading["timeout_ms"].get<int>();
        }
        
        // 加载监控参数
        if (config.contains("monitor")) {
            auto& monitor = config["monitor"];
            monitor_params_.enable_latency_monitor = monitor["enable_latency_monitor"].get<bool>();
            monitor_params_.enable_throughput_monitor = monitor["enable_throughput_monitor"].get<bool>();
            monitor_params_.enable_error_monitor = monitor["enable_error_monitor"].get<bool>();
            monitor_params_.history_size = monitor["history_size"].get<int>();
            monitor_params_.log_level = monitor["log_level"].get<std::string>();
        }
        
        // 验证配置
        if (!validateConfig()) {
            std::cerr << "Invalid configuration" << std::endl;
            return false;
        }
        
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Failed to load config: " << e.what() << std::endl;
        return false;
    }
}

bool ConfigManager::saveConfig(const std::string& filename) const {
    try {
        std::lock_guard<std::mutex> lock(mutex_);
        
        nlohmann::json config;
        
        // 保存CTP配置
        config["ctp"] = {
            {"front_address", ctp_config_.front_address},
            {"broker_id", ctp_config_.broker_id},
            {"user_id", ctp_config_.user_id},
            {"password", ctp_config_.password},
            {"app_id", ctp_config_.app_id},
            {"auth_code", ctp_config_.auth_code}
        };
        
        // 保存交易参数
        config["trading"] = {
            {"max_position", trading_params_.max_position},
            {"max_order_size", trading_params_.max_order_size},
            {"max_slippage", trading_params_.max_slippage},
            {"min_liquidity", trading_params_.min_liquidity},
            {"risk_limit", trading_params_.risk_limit},
            {"max_retry_count", trading_params_.max_retry_count},
            {"retry_interval_ms", trading_params_.retry_interval_ms},
            {"timeout_ms", trading_params_.timeout_ms}
        };
        
        // 保存监控参数
        config["monitor"] = {
            {"enable_latency_monitor", monitor_params_.enable_latency_monitor},
            {"enable_throughput_monitor", monitor_params_.enable_throughput_monitor},
            {"enable_error_monitor", monitor_params_.enable_error_monitor},
            {"history_size", monitor_params_.history_size},
            {"log_level", monitor_params_.log_level}
        };
        
        JsonUtils::saveToFile(filename, config);
        
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Failed to save config: " << e.what() << std::endl;
        return false;
    }
}

CTPConfig ConfigManager::getCTPConfig() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return ctp_config_;
}

ConfigManager::TradingParams ConfigManager::getTradingParams() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return trading_params_;
}

ConfigManager::MonitorParams ConfigManager::getMonitorParams() const {
    std::lock_guard<std::mutex> lock(mutex_);
    return monitor_params_;
}

void ConfigManager::updateCTPConfig(const CTPConfig& config) {
    std::lock_guard<std::mutex> lock(mutex_);
    ctp_config_ = config;
}

void ConfigManager::updateTradingParams(const TradingParams& params) {
    std::lock_guard<std::mutex> lock(mutex_);
    trading_params_ = params;
}

void ConfigManager::updateMonitorParams(const MonitorParams& params) {
    std::lock_guard<std::mutex> lock(mutex_);
    monitor_params_ = params;
}

void ConfigManager::setDefaultConfig() {
    // 设置默认CTP配置
    ctp_config_.front_address = "tcp://180.168.146.187:10101";
    ctp_config_.broker_id = "9999";
    ctp_config_.user_id = "test";
    ctp_config_.password = "test";
    ctp_config_.app_id = "simnow_client_test";
    ctp_config_.auth_code = "0000000000000000";
    
    // 设置默认交易参数
    trading_params_.max_position = 100.0;
    trading_params_.max_order_size = 10.0;
    trading_params_.max_slippage = 0.001;
    trading_params_.min_liquidity = 1000;
    trading_params_.risk_limit = 0.1;
    trading_params_.max_retry_count = 3;
    trading_params_.retry_interval_ms = 1000;
    trading_params_.timeout_ms = 5000;
    
    // 设置默认监控参数
    monitor_params_.enable_latency_monitor = true;
    monitor_params_.enable_throughput_monitor = true;
    monitor_params_.enable_error_monitor = true;
    monitor_params_.history_size = 1000;
    monitor_params_.log_level = "INFO";
}

bool ConfigManager::validateConfig() const {
    // 验证CTP配置
    if (ctp_config_.front_address.empty() ||
        ctp_config_.broker_id.empty() ||
        ctp_config_.user_id.empty() ||
        ctp_config_.password.empty()) {
        return false;
    }
    
    // 验证交易参数
    if (trading_params_.max_position <= 0 ||
        trading_params_.max_order_size <= 0 ||
        trading_params_.max_slippage < 0 ||
        trading_params_.min_liquidity <= 0 ||
        trading_params_.risk_limit < 0 ||
        trading_params_.max_retry_count < 0 ||
        trading_params_.retry_interval_ms <= 0 ||
        trading_params_.timeout_ms <= 0) {
        return false;
    }
    
    // 验证监控参数
    if (monitor_params_.history_size <= 0) {
        return false;
    }
    
    return true;
}

} // namespace hft 